package com.hux.vvownerclub.service.vv.impl;

import com.hux.frame.util.ContantsUtil;
import com.hux.vvownerclub.dbmodel.TInbox;
import com.hux.vvownerclub.dbmodel.TInboxSession;
import com.hux.vvownerclub.dbmodel.TUser;
import com.hux.vvownerclub.service.vv.InboxService;
import com.hux.vvownerclub.util.SystemCodes;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: xiang
 * Date: 13-9-10
 * Time: 下午4:35
 */
public class InboxServiceImpl implements InboxService {

    //用户留言
    private static final String C_0601 = "0601";

    //系统留言
    private static final String C_0602 = "0602";

    @Override
    @Before(Tx.class)
    public void postInboxMsg(int formUser, int toUser, String inboxMsg) {

        TUser fu = TUser.dao.findById(formUser);
        TUser tu = TUser.dao.findById(toUser);
        if (null != fu && null != tu) {

            //查询是否已经存在会话
            TInboxSession session = TInboxSession.dao.findFirst("select * from t_inboxsession t where t.fromuser = ? and t.touser = ?",
                    formUser, toUser);

            Date postDate = new Date();

            //不存在就新增
            if (null == session) {

                //需要新增两条记录
                TInboxSession tus = new TInboxSession();
                tus.set("fromuser", formUser);
                tus.set("sessionuser", toUser);
                tus.set("last_con", "发给<a target=\"_blank\" href=\"/u/" + tu.get("url") + "\">" + tu.get("name") + "</a>：" + inboxMsg);
                tus.set("last_rtime", postDate);
                tus.set("con_num", 1);
                tus.save();
                tus.set("sid",tus.get("id"));
                tus.update();

                TInboxSession fus = new TInboxSession();
                fus.set("sid",tus.get("id"));
                fus.set("fromuser", toUser);
                fus.set("sessionuser", formUser);
                fus.set("last_con", "发给<a target=\"_blank\" href=\"/u/" + tu.get("url") + "\">" + tu.get("name") + "</a>：" + inboxMsg);
                fus.set("last_rtime", postDate);
                fus.set("con_num", 1);
                fus.save();

            } else {

            }

            TInbox inbox = new TInbox();
            inbox.set("fromuser", formUser);
            inbox.set("touser", toUser);
            inbox.set("content", inboxMsg);
            inbox.set("rtime", new Date());
            inbox.set("type", C_0601);
            inbox.set("isdel", SystemCodes.Y);
            inbox.save();
        }
    }
}
